from loguru import logger
from fastapi import APIRouter,Depends
from sqlalchemy import desc
from model.equipment_sensor import EquipmentSensorTable,Item,UpdateInfo
from model.equipment_drill import EquipmentDrill
from vendor.extend.courier import *
from vendor.extend.conversion import is_positive_integer
from sqlalchemy.orm import Session
from db.mysql import get_db

EquipmentSensor = APIRouter()

@EquipmentSensor.post('/add')
async def settings(item: Item, db: Session = Depends(get_db)):
    item_dict = item.dict()
    raster_total=item_dict.get('raster_total',0)
    raster_data=item_dict.get('raster_data',[])
    drill_id=item_dict.get('drill_id',0)
    if not raster_data:
        return Error(msg='光栅数据不能为空')

    if raster_total!=len(raster_data):
        return Error(msg='光栅数据总数量必须和光栅总数量一致')

    if not is_positive_integer(drill_id):
        return Error(msg='钻孔ID必须为正整数')
    for idx, val in enumerate(raster_data):
        depth=val.get('depth',0)
        wavelength=val.get('wavelength',0)
        factor=val.get('factor',0)
        if depth==0 or isinstance(depth, (int, float)):
            return Error(msg=f'光栅{(idx+1)}深度不能为空')
        if wavelength==0 or isinstance(wavelength, (int, float)):
            return Error(msg=f'光栅{(idx+1)}设计波长λ不能为空')
        if factor==0 or isinstance(wavelength, (int, float)):
            return Error(msg=f'光栅{(idx+1)}比例系数K为空')

    result = db.query(EquipmentDrill.id,EquipmentDrill.equipment_id).filter_by(id=drill_id).first()
    if not result:
        return Error(msg='钻孔不存在')

    add_data=EquipmentSensorTable(
                                    equipment_id=result.equipment_id,
                                    drill_id=result.id,
                                    numbering= item_dict.get('numbering',''),
                                    raster_total= raster_total,
                                    raster_data=raster_data,
                                    create_time=int(time.time())
                                )

    try:
        # 执行一些数据库操作
        db.add(add_data)
        db.flush()
        db.refresh(add_data)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("传感器信息 添加 出错:{}", e)


    return Success(data={'sensor_id':add_data.id,'drill_id':result.id,'equipment_id':result.equipment_id,'create_time':add_data.create_time})


@EquipmentSensor.post('/edit')
async def edit(item: UpdateInfo, db: Session = Depends(get_db)):
    item_dict = item.dict()
    sensor_id=item_dict.get('sensor_id',0)
    raster_total=item_dict.get('raster_total',0)
    raster_data=item_dict.get('raster_data',[])
    drill_id=item_dict.get('drill_id',0)
    if not is_positive_integer(sensor_id):
        return Error(msg='传感器ID必须为正整数')

    if not raster_data:
        return Error(msg='光栅数据不能为空')

    if raster_total!=len(raster_data):
        return Error(msg='光栅数据总数量必须和光栅总数量一致')

    for idx, val in enumerate(raster_data):
        depth=val.get('depth',0)
        wavelength=val.get('wavelength',0)
        factor=val.get('factor',0)
        if depth==0 or isinstance(depth, (int, float)):
            return Error(msg=f'光栅{(idx+1)}深度不能为空')
        if wavelength==0 or isinstance(wavelength, (int, float)):
            return Error(msg=f'光栅{(idx+1)}设计波长λ不能为空')
        if factor==0 or isinstance(wavelength, (int, float)):
            return Error(msg=f'光栅{(idx+1)}比例系数K为空')

    if not is_positive_integer(drill_id):
        return Error(msg='钻孔ID必须为正整数')

    result = db.query(EquipmentDrill.id,EquipmentDrill.equipment_id).filter_by(id=drill_id).first()
    if not result:
        return Error(msg='钻孔不存在')

    sensorData={
        'drill_id':drill_id,
        'equipment_id':result.equipment_id,
        'numbering': item_dict.get('numbering',''),
        'raster_total':raster_total,
        'raster_data':raster_data,
        'update_time':int(time.time())
    }
    updated_count=None
    try:
        # 执行一些数据库操作
        updated_count = db.query(EquipmentSensorTable).filter_by(id=sensor_id).update(sensorData)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("传感器信息 更新 出错:{}", e)

    if updated_count:
        return Success(data=sensorData)
    else:
        return Error(msg='光栅数据修改失败')


@EquipmentSensor.get('/list')
async def getlist(drill_id:int, db: Session = Depends(get_db)):
    if not is_positive_integer(drill_id):
        return Error(msg='钻孔ID必须为正整数')
    list_data=db.query(EquipmentSensorTable).filter_by(drill_id=drill_id).order_by(desc("id")).all()
    user_list = [{
        "id":info.id,
        "numbering":info.numbering,
        "raster_total":info.raster_total,
        "raster_data":info.raster_data,
        "equipment_id":info.equipment_id,
        "drill_id":info.drill_id,
        "create_time":info.create_time,
        "update_time":info.update_time
    } for info in list_data]  # 转换为字典列表
    return Success(data=user_list)



@EquipmentSensor.get('/info')
async def getinfo(sensor_id:int, db: Session = Depends(get_db)):
    if not is_positive_integer(sensor_id):
        return Error(msg='传感器ID必须为正整数')
    info = db.query(EquipmentSensorTable).filter_by(id=sensor_id).first()
    if info:
        return Success(data={
            "id":info.id,
            "numbering":info.numbering,
            "raster_total":info.raster_total,
            "raster_data":info.raster_data,
            "equipment_id":info.equipment_id,
            "drill_id":info.drill_id,
            "create_time":info.create_time,
            "update_time":info.update_time
        })
    else:
        return Error(msg='未找到传感器相关数据')